package chapter2.eg1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import org.junit.Test;

public class EchoClient {
  @Test
  public void testClient() throws IOException {
    SocketChannel channel = SocketChannel.open();
    channel.connect(new InetSocketAddress("127.0.0.1", 8080));
    request(channel);
    handleResponse(channel);
  }

  private void request(SocketChannel channel) throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap("Hello, I'm client. ".getBytes());
    channel.write(buffer);
  }

  private void handleResponse(SocketChannel channel) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    channel.read(buffer);
    buffer.flip();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    System.out.println("Client receives message: ");
    System.out.println(new String(bytes, StandardCharsets.UTF_8));
  }

}
